package com.zzmcc.jms.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.zzmcc.base.BaseController;
import com.zzmcc.common.AuthorizeInterceptor;
import com.zzmcc.jms.model.News;

import com.jfinal.ext.kit.PoiKit.Pair;
import com.jfinal.ext.kit.PoiKit.SheetData;
import net.dreamlu.event.EventKit;
import net.dreamlu.event.core.ApplicationEvent;

import java.util.ArrayList;
import java.util.List;

import static com.zzmcc.jms.common.ModelConfigWms.TABLE_News;

@Before(AuthorizeInterceptor.class)
public class NewsController extends BaseController {

	public void index() {
		Page<News> pager = News.dao.paginate(
				getParaToInt("pageNum", 1),
				getParaToInt("numPerPage", 20),
				"select * ", 
				" from " + TABLE_News ) ;

		setAttr("pager",pager);
		render("../news_list.html");
	}
	public void add() {
		render("../news_input.html");
	}
	
	public void checkIsNotExist(){
		renderJson(checkIsNotExist(TABLE_News, "id", getPara("news.id")));
	}
	
	public void checkNameIsNotExist(){
		renderJson(checkIsNotExist(TABLE_News, "name", getPara("news.name")));
	}
	
	public void save() {
		News s = getModel(News.class, "news");
		boolean temp =s.save();
		if (temp) {
			EventKit.postEvent(new saveEvent(s));
		}
		renderDWZSuccessJson("消息发布成功！");
	}

	public class saveEvent extends ApplicationEvent {

		private static final long serialVersionUID = 6994987952247306131L;

		public saveEvent(Object source) {
			super(source);
			System.out.print("saveEvent");
		}

	}
	
	public void edit() {
		setAttr("news",News.dao.findById(getPara("id")));
		render("../news_input.html");
	}
	
	public void update() {
		News s = getModel(News.class, "news");
		s.update();
		renderDWZSuccessJson("消息修改成功！");
	}
	
	public void delete() {
		String[] ids = getParaValues("ids");
		for(String id:ids){
			News.dao.deleteById(id);
		}
		renderDWZSuccessJson("删除成功!");
	}

	public void export(){

		List<Record> list = Db.find("show full columns from jms_news");
		List<Record> newsList = Db.find("select * from jms_news");

		List<Pair> titles = new ArrayList<Pair>();

		for(Record r : list) {

			String value = r.get("Comment");

			String key = r.get("Field");

			titles.add(new Pair(key, value));
		}
		String sheetName ="news";
		SheetData sheetData = new SheetData(titles,newsList,sheetName);
		PoiRender excel = PoiRender.me(sheetData);
		render(excel.fileName("jms_news.xls"));


	}

}
